<template>
  <div ref="chart" style="height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts'
import { getRegTrend } from '@/api/analysis'

export default {
  name: 'RegTrend',
  props: {
    type: {
      type: String,
      default: 'month'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    type() {
      this.refreshData()
    }
  },
  mounted() {
    this.initChart()
    this.refreshData()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value'
        },
        title: {
          text: '总注册人数：0人',
          right: '5%',
          top: '5%'
        }
      })
    },
    async refreshData() {
      try {
        const res = await getRegTrend({ type: this.type })
        const option = {
          xAxis: {
            data: res.data.timePoints
          },
          series: [{
            name: '注册人数',
            type: 'line',
            data: res.data.counts,
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
                { offset: 1, color: 'rgba(58, 77, 233, 0.1)' }
              ])
            }
          }],
          title: {
            text: `总注册人数：${res.data.totalRegistrations}人`
          }
        }
        this.chart.setOption(option)
      } catch (error) {
        console.error('加载注册趋势失败:', error)
      }
    },
    resizeHandler() {
      this.chart.resize()
    }
  }
}
</script>
